<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\video\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\video\home\VideoApi;

use app\video\logic\Vodlogic;

use app\erp\model\ErpGoods;
use think\facade\Hook;
use util\Tree;
/**
 * 视频管理控制器
 * @package app\video\admin
 */
class Index extends Admin
{
    /**
     * 首页
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index($classid = ''){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        
        // 获取筛选
        $map = $this->getMap();

        //数据获取
        $data = input();
        $attestation_id = isset($data['attestation_id']) ? $data['attestation_id'] : 0;
        if($attestation_id > 0) $map[] = ['attestation_id', '=', $attestation_id];
		
        if($classid > 0) $map[] = ['video_classid', '=', $classid];

        // 获取排序
        $order = $this->getOrder();
        $order =  $order?$order: 'is_recommend desc, create_time desc';

		
        // 数据列表
		$map[] = ['father_play_id', '=', 0];
		$map[] = ['play_type', 'in', '1,2,3'];
        $data_list = model('VideoPlay', 'model')->useGlobalScope(false) -> where($map) -> order($order) -> paginate();//dump($data_list);die;

        // 分页数据
        $page = $data_list->render();

        $rel_list =[];
        foreach ($data_list as $key => $value) {
            $rel_list[$key] = $value->toArray();
            $rel_list[$key]['file_size']                = formatBytes($value['file_size']);
            $rel_list[$key]['play_operation_status']    = $value['play_operation_status'];
            $rel_list[$key]['author']                   = $value['get_uc_member']['nick_name'].'(UID:'.$value['uid'].')';
			// if($value['father_play_id'] > 0) $rel_list[$key]['play_type'] = 2;
        } //dump($rel_list);die;
        // 详情
        $btn_details = [
            'title' => '详情',
            'icon'  => 'fa fa-fw fa-bookmark',
            //'class' => 'btn-default',
            'href'  => url('details', ['id' => '__id__'])
        ];
		
		// 评论列表
        $btn_comment = [
            'title' => '评论列表',
            'icon'  => 'fa fa-fw fa-bookmark',
            'href'  => url('comment/index', ['id' => '__id__'])
        ];
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('视频管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为username
            ->setTableName('video_play') // 设置数据表名
            //->setSearch(['id' => '艺人ID', 'artist_name' => '艺人名称', 'uid' => '会员UID']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['__INDEX__', '序号'],
                ['author', '上传作者', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['main_title', '视频标题'],
                //['description', '视频描述'],
                ['file_size', '视频大小'],
                ['play_type', '视频类型', 'status', '', [1 => '短视频:default', 2 => '长视频:danger', 3 => '系统视频:success']],
                ['play_operation_status', '人审状态', 'status', '', [0 => '待审核:default', 1 => '正常:success', 2 => '已屏蔽:danger', 3 => '上传中:danger']],
                ['create_time', '创建时间', 'datetime'],
                ['is_recommend', '首页推荐', 'switch'],
                ['play_status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->setSearchArea([
                ['text', 'main_title', '视频标题', 'like'],
                ['daterange', 'create_time', '创建时间'],
                ['select', 'play_type', '视频类型', '', '', ['1' => '短视频', '2' =>'长视频', '3' => '系统视频']],
                ['select', 'play_operation_status', '审核状态', '', '', ['0' => '待审核','1' => '正常', '2' => '已屏蔽', '3' => '上传中']],
                ['select', 'is_original', '视频来源', '', '', ['0' => '转载', '1' => '原创']],
                ['select', 'is_recommend', '首页推荐', '', '', ['0' => '否', '1' => '是']],
                ['text', 'uid', '用户UID'],
            ])
            //->addFilter(['play_operation_status']) // 添加筛选
            ->addOrder('file_size,create_time') // 添加排序
            ->addRightButton('custom', $btn_details, true) // 添加授权按钮
            ->addTopButtons('delete') // 批量添加顶部按钮
            ->addTopButton('custom', ['title' => '添加圈子视频', 'href' => url('video/index/add',['type'=>'1'])],true)
            ->addTopButton('custom', ['title' => '添加推荐视频', 'href' => url('video/index/add')],true)
            //->addRightButtons('delete') // 批量添加右侧按钮
			//->addRightButton('custom', $btn_comment, true) // 添加授权按钮
			->addRightButton('edit', '视频详情编辑', true) // 添加授权按钮
            ->setPages($page) // 设置分页数据
            ->setRowList($rel_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 审核列表
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function examine(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
   
        // 获取排序
        $order = $this->getOrder();
        if(!$order) $order = 'create_time desc';

        // 获取筛选
        $map = $this->getMap();

        //数据获取
        $data = input();
        $attestation_id = isset($data['attestation_id']) ? $data['attestation_id'] : 0;
        if($attestation_id > 0) $map[] = ['attestation_id', '=', $attestation_id];

        //tab
        $list_tab = [
            'tab1' => ['title' => '待审核', 'url' => url('examine', ['group' => 'tab1'])],
            'tab2' => ['title' => '已通过', 'url' => url('examine', ['group' => 'tab2'])],
            'tab3' => ['title' => '已屏蔽', 'url' => url('examine', ['group' => 'tab3'])],
        ];

        // 数据列表
        $group = isset($data['group']) ? $data['group'] : 'tab1';
        switch ($group) {
            case 'tab1':
                $map[] = ['play_operation_status', '=', 0];
                break;
            case 'tab2':
                $map[] = ['play_operation_status', '=', 1];
                break;
            case 'tab3':
                $map[] = ['play_operation_status', '=', 2];
                break;
        }

        //查询状态为待审核的视频列表
        $data_list = model('VideoPlay', 'model') -> where($map) ->order($order) -> paginate();
        $rel_list =[];
        foreach ($data_list as $key => $value) {
            if(!isset($value -> getVideoPlayAiExamine -> examine_status)) continue;
            $rel_list[$key] = $value->toArray();
            $rel_list[$key]['examine_status']       = isset($value -> getVideoPlayAiExamine -> examine_status) ? $value -> getVideoPlayAiExamine -> examine_status : 0;//机审状态
            $rel_list[$key]['file_size']            = formatBytes($value['file_size']);
            $rel_list[$key]['artificial_status']    = $value -> play_operation_status;
            $rel_list[$key]['author']                   = $value['get_uc_member']['nick_name'].'(UID:'.$value['uid'].')';
        } 
        // 分页数据
        $page = $data_list->render();

        // 详情
        $btn_details = [
            'title' => '详情',
            'icon'  => 'fa fa-fw fa-bookmark',
            //'class' => 'btn-default',
            'href'  => url('details', ['id' => '__id__'])
        ];
        // 添加智能审核
        $btn_ai_examine = [
            'title' => '智能AI',
            'icon'  => 'fa fa-fw fa-bookmark',
            //'class' => 'btn-default',
            'href'  => url('add', ['attestation_id' => $attestation_id])
        ];
        // 通过
        $btn_artificial_examine_yse = [
            'title' => '通过',
            'icon'  => 'fa fa-fw fa-bookmark',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href'  => url('buildAuditContent_yes', ['ids' => '__id__'])
        ];

        // 屏蔽
        $btn_artificial_examine_no = [
            'title' => '屏蔽',
            'icon'  => 'fa fa-fw fa-bookmark',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href'  => url('buildAuditContent_no', ['ids' => '__id__'])
        ];

        // 批量审核
        $btn_artificial_yes = [
            'title' => '批量通过',
            'icon'  => 'fa fa-fw fa-bookmark',
            'class' => 'btn btn-success ajax-post confirm',
            'href'  => url('buildAuditContent_yes')
        ];
        // 批量屏蔽
        $btn_artificial_no = [
            'title' => '批量屏蔽',
            'icon'  => 'fa fa-fw fa-bookmark',
            'class' => 'btn btn-warning ajax-post confirm',
            'href'  => url('buildAuditContent_no')
        ];
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('视频审核') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为username
            ->setTableName('video_play') // 设置数据表名
            ->setTabNav($list_tab,  $group)
            //->setSearch(['id' => '艺人ID', 'artist_name' => '艺人名称', 'uid' => '会员UID']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['author', '上传作者', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['main_title', '视频标题'],
                ['description', '视频描述'],
                ['play_type', '视频类型', 'status', '', [1 => '精华版:default', 2 => '完整版:danger', 3 => '系统视频:success']],
                ['file_size', '视频大小'],
                ['create_time', '创建时间', 'datetime'],
                ['examine_status', '机审状态', 'status', '', [0 => '待审核:default', 1 => '审核中:warning', 2 => '已通过:success', 3 => '已屏蔽:danger']],
                ['artificial_status', '人审状态', 'status', '', [0 => '待审核:default', 1 => '已通过:success', 2 => '已屏蔽:danger']],
                ['right_button', '操作', 'btn']
            ])
            ->setSearchArea([
                ['text', 'main_title', '视频标题', 'like'],
                ['daterange', 'create_time', '创建时间'],
                ['select', 'play_type', '视频类型', '', '', ['1' => '短视频', '2' => '长视频']],
                //['select', 'play_operation_status', '审核状态', '', '', ['0' => '待审核','1' => '正常', '2' => '已屏蔽', '3' => '上传中']],
                ['select', 'is_original', '视频来源', '', '', ['0' => '转载', '1' => '原创']],
                //['select', 'is_recommend', '首页推荐', '', '', ['0' => '否', '1' => '是']],
                ['text', 'uid', '用户UID'],
            ])
            ->addOrder('create_time') // 添加排序
            //->addTimeFilter('create_time', '', ['开始时间', '结束时间'])
            ->addRightButton('custom', $btn_details, true) // 详情
            //->addRightButton('custom', $btn_ai_examine, true) // 智能审核
            ->addRightButton('custom', $btn_artificial_examine_yse) // 通过
            ->addRightButton('custom', $btn_artificial_examine_no) // 屏蔽
            ->replaceRightButton(['artificial_status' => 1], '<button class="btn btn-danger btn-xs" type="button" disabled>不可操作</button>') // 修改id为1的按钮
            //->replaceRightButton(['artificial_status' => 2], '<button class="btn btn-danger btn-xs" type="button" disabled>不可操作</button>') // 修改id为1的按钮

            ->addTopButton('custom', $btn_artificial_yes) // 顶部 批量人工审核 通过
            ->addTopButton('custom', $btn_artificial_no) // 顶部 批量人工审核 屏蔽
            //->addTopButtons('enable,disable,delete') // 批量添加顶部按钮
            //->addRightButtons('delete') // 批量添加右侧按钮
            ->setPages($page) // 设置分页数据
            ->setRowList($rel_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 人工审核 批量通过
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function buildAuditContent_yes($ids = []){
        //批量审核最多允许20个
        $list = model('VideoPlay', 'model') -> where('id', 'in', $ids) -> order('create_time desc') ->limit(20) -> select();//dump($list);die;
        foreach ($list as $key => $value) {
            $rel_list[] = [
                'VideoId' => $value['video_id'],
                'Status'  => 'Normal',
            ];
        }
        //视频通过
        $result = controller('Vodlogic', 'logic') -> buildAuditContent($rel_list);
        if($result['code'] == 200){
            $this -> success('操作成功');
        }else{
            $this -> error('操作失败');
        }
    }

    /**
     * 人工审核 批量屏蔽
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function buildAuditContent_no($ids = []){
        //批量审核最多允许20个
        $list = model('VideoPlay', 'model') -> where('id', 'in', $ids) -> order('create_time desc') ->limit(20) -> select();
        $rel_list = [];
        foreach ($list as $key => $value) {
            $rel_list[] = [
                'VideoId' => $value['video_id'],
                'Status'  => 'Blocked',
                'Reason'  => '后台批量屏蔽',
            ];
        }
        $result = controller('Vodlogic', 'logic') -> buildAuditContent($rel_list);
        if($result['code'] == 200){
            $this -> success('操作成功');
        }else{
            $this -> error('操作失败');
        }
    }

    /**
     * 详情
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function details($id = []){
        $map = [];
        $rel = model('VideoPlay')->useGlobalScope(false) ->where($map) -> find($id);
        if($rel->play_operation_status == 3) $this -> error('该视频暂时无法查看');
        $playAuth = controller('Vodlogic', 'logic') -> getVideoPlayAuth($rel -> video_id);
        $playInfo = controller('Vodlogic', 'logic') -> getPlayInfo($rel -> video_id);
        $play_id = $id;
        $support_times = $rel -> support_times;
        $comment_times = $rel -> comment_times;
        $report_times = $rel -> report_times;
		
		$cVideoId = '';
		$cplayAuth = '';
        //判断是否存在完整版
        if($rel->father_play_id > 0){
            $rel_father = model('VideoPlay') ->where($map) -> find($rel->father_play_id);
            $play_id = $rel_father->id;
            $support_times = $rel_father -> support_times;
            $comment_times = $rel_father -> comment_times;
            $report_times = $rel_father -> report_times;
			
			$cVideoId = $rel_father -> video_id;//完整版视频ID
			$cplayAuth = controller('Vodlogic', 'logic') -> getVideoPlayAuth($cVideoId);
        }
		
        //查询视频详情
        if($playInfo['code'] == 200 || $playAuth['code'] == 200){
            $list_video = [];
            foreach ($playInfo['data']['PlayInfoList']['PlayInfo'] as $key => $value) {
                $list_video[] = [
                    'Title'         => $playInfo['data']['VideoBase']['Title'],
                    'Describe'      => $rel -> description,
                    'VideoId'       => $rel -> video_id,
                    'Duration'      => secToTime($playInfo['data']['VideoBase']['Duration']),
                    'Size'          => formatBytes($value['Size']),
                    'Width'         => $value['Width'],
                    'Height'        => $value['Height'],
                    'FPS'           => $value['Fps'],
                    'Bitrate'       => $value['Bitrate'],
                    'Format'        => $value['Format'],
                    'Definition'    => $value['Definition'].'-'.model('VideoPlay') -> getDefinitionAttr($value['Definition']),
                ];
            }//dump($playAuth);

            //标签
            $info = model('VideoPlayLabelRelation') ->getListByPlayid($rel -> id);
            $label_arr = [];
            foreach ($info['data'] as $key => $value) {
                $label_arr[] = $value -> get_video_play_class_label -> title;
            }
            $label_str = implode(' | ', $label_arr);

            //分类
            $lists = model('VideoPlayClass') -> select()->toArray();
            $class_arr = Tree::getParents($lists, $id = $rel->video_classid);
            $ClassTitle='';
            foreach ($class_arr as $key => $value) {
                $ClassTitle = !$ClassTitle ? $value['title'] : $ClassTitle.' - '.$value['title'];
            }

            //视频播放次数
            $map = [];
            $map[] = ['play_id', '=', $play_id];
            $map[] = ['seconds', '>', 0];
            $video_plays = model('VideoPlayWatchcount') -> where($map) -> count();//播放次数
            $video_plays_sum = model('VideoPlayWatchcount') -> where($map) -> sum('seconds');//播放总时长
            $video_plays_average = $video_plays > 0 ? $video_plays_sum/$video_plays : 0;//平均播放时长
            //小于百分之10的人数
            $map = [];
            $map[] = ['play_id', '=', $play_id];
            $map[] = ['seconds', '>', 0];
            $map[] = ['seconds', '<=', $playInfo['data']['VideoBase']['Duration']*0.1];
            $video_plays_10t = model('VideoPlayWatchcount') -> where($map) -> count();//播放次数
            $video_plays_10b = $video_plays > 0 ? round(($video_plays_10t/$video_plays*100), 2).'%': '0%';//播放次数
            //百分之10~30的人数
            $map = [];
            $map[] = ['play_id', '=', $play_id];
            $map[] = ['seconds', '>', $playInfo['data']['VideoBase']['Duration']*0.1];
            $map[] = ['seconds', '<=', $playInfo['data']['VideoBase']['Duration']*0.3];
            $video_plays_30t = model('VideoPlayWatchcount') -> where($map) -> count();//播放次数
            $video_plays_30b = $video_plays > 0 ? round(($video_plays_30t/$video_plays*100), 2).'%': '0%';//播放次数
            //百分之30~60的人数
            $map = [];
            $map[] = ['play_id', '=', $play_id];
            $map[] = ['seconds', '>', 0];
            $map[] = ['seconds', '>', $playInfo['data']['VideoBase']['Duration']*0.3];
            $map[] = ['seconds', '<=', $playInfo['data']['VideoBase']['Duration']*0.6];
            $video_plays_60t = model('VideoPlayWatchcount') -> where($map) -> count();//播放次数
            $video_plays_60b = $video_plays > 0 ? round(($video_plays_60t/$video_plays*100), 2).'%': '0%';//播放次数
            //百分之60~90的人数
            $map = [];
            $map[] = ['play_id', '=', $play_id];
            $map[] = ['seconds', '>', 0];
            $map[] = ['seconds', '>', $playInfo['data']['VideoBase']['Duration']*0.6];
            $map[] = ['seconds', '<=', $playInfo['data']['VideoBase']['Duration']*0.9];
            $video_plays_90t = model('VideoPlayWatchcount') -> where($map) -> count();//播放次数
            $video_plays_90b = $video_plays > 0 ? round(($video_plays_90t/$video_plays*100), 2).'%': '0%';//播放次数
            //百分之90~100的人数
            $map = [];
            $map[] = ['play_id', '=', $play_id];
            $map[] = ['seconds', '>', 0];
            $map[] = ['seconds', '>', $playInfo['data']['VideoBase']['Duration']*0.9];
            $video_plays_100t = model('VideoPlayWatchcount') -> where($map) -> count();//播放次数
            $video_plays_100b = $video_plays > 0 ? round(($video_plays_100t/$video_plays*100), 2).'%': '0%';//播放次数
            //dump($ClassTitle);

            //如果是精简版 调取完整版数据
            $cPlayId = $rel->father_play_id > 0 ? $rel->father_play_id : $rel -> id;
            $videoInfo = [
                'PlayId'        => $rel -> id,
                'cPlayId'       => $cPlayId,
                'sPlayId'       => $rel -> son_play_id,
                'Title'         => $rel -> main_title,
                'Describe'      => $rel -> description,
                'VideoId'       => $rel -> video_id,
                'Duration'      => secToTime($playInfo['data']['VideoBase']['Duration']),
                'PlayAuth'      => $playAuth['data']['PlayAuth'],
                'ClassTitle'    => $ClassTitle,
                'IsOriginal'    => model('VideoPlay') ->getIsOriginal($rel -> is_original),
                'IsRecommend'   => model('VideoPlay') ->getIsRecommend($rel -> is_recommend),
                'PlayType'      => model('VideoPlay') ->getPlayType($rel -> play_type),
                'support_times' => $support_times,
                'comment_times' => $comment_times,
                'report_times'  => $report_times,
                'video_plays'       => $video_plays,
                'video_plays_sum'   => secToTime($video_plays_sum),
                'video_plays_average'   => secToTime($video_plays_average),
                'label_str'         => $label_str,
                'video_plays_10t'       => $video_plays_10t,
                'video_plays_10b'       => $video_plays_10b,
                'video_plays_30t'       => $video_plays_30t,
                'video_plays_30b'       => $video_plays_30b,
                'video_plays_60t'       => $video_plays_60t,
                'video_plays_60b'       => $video_plays_60b,
                'video_plays_90t'       => $video_plays_90t,
                'video_plays_90b'       => $video_plays_90b,
                'video_plays_100t'       => $video_plays_100t,
                'video_plays_100b'       => $video_plays_100b,
            ];
            $this->assign('videoInfo', $videoInfo);
            $this->assign('list_video', $list_video);
        }else{
            $this -> error('该视频暂时无法查看, 或资源丢失');
        }

        return $this->fetch();
    
    }

    /**
     * 视频删除
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function delete($ids = []){
        if(count($ids) >10){
            $this -> error('最多允许删除10个！');
        }
        //批量审核最多允许10个
        $list = model('VideoPlay', 'model') -> where('id', 'in', $ids) -> order('create_time desc') ->limit(10) -> select();

        $video_id_arr =[];
        $video_id_destroy =[];//删除 - 扣除作品数
        $video_id_delete =[];//删除 - 不扣除作品数
        foreach ($list as $key => $value) {
            //判断是否是精简视频
            if($value['father_play_id'] > 0){
                $video_id_delete[] = $value['father_play_id'];
            }
            //判断是否是 完整版视频
            $map = [];
            $map['father_play_id'] = $value['id'];
            if($relinfo = model('VideoPlay', 'model')->where($map) -> find()){
                $video_id_delete[] = $relinfo->id;
            }


            if($value['play_operation_status'] == 1){
				$video_id_destroy[] = $value['id'];
			}else{
				$video_id_delete[] = $value['id'];
			}
			$video_id_arr[] = $value['video_id'];
        }
        $videoIds = implode(',', $video_id_arr);
        //删除 阿里云 数据
        $rel = controller('Vodlogic', 'logic') -> deleteVideos($videoIds);

        $rel1 = model('VideoPlay', 'model') -> destroy($video_id_destroy);
		
		$map = [];
		$map['id'] = $video_id_delete;
		$rel2 = model('VideoPlay', 'model') -> where($map) -> delete();
        
        if($rel['code'] == 200){
            $this -> success('删除成功');
        }else{
            $this -> error('删除失败');
        }
    
    }
	
	/**
     * 视频编辑
     * @author shiqiang
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
	public function edit($id = 0){
		if ($id === 0) $this->error('缺少参数');
		$play_id = $id;

		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');

			$main_title     = isset($data['main_title']) ? $data['main_title'] : '';
			$description    = isset($data['description']) ? $data['description'] : '';
			$play_type      = isset($data['play_type']) ? $data['play_type'] : '';
			$is_immerse     = isset($data['is_immerse']) ? $data['is_immerse'] : '';
			$is_rotate      = isset($data['is_rotate']) ? $data['is_rotate'] : '';
			$play_status    = isset($data['play_status']) ? $data['play_status'] : '';
			$is_recommend   = isset($data['is_recommend']) ? $data['is_recommend'] : '';
			$is_original    = isset($data['is_original']) ? $data['is_original'] : '';
			$video_classid	= isset($data['video_classid']) ? $data['video_classid'] : '';
			$customLabel 	= isset($data['customLabel']) ? $data['customLabel'] : '';
			// $label 			= isset($data['label']) ? $data['label'] : '';
            $play_operation_status = isset($data['play_operation_status']) ? $data['play_operation_status'] : '';
			$label = [];
            $goods_id_array  = isset($data["goods_id_array"]) ? $data["goods_id_array"] : [];//$goods_id_array=[24, 25];//临时
			if($main_title == '' || $description == '' || $video_classid == ''){
				$this -> error('数据格式错误');
			}

            //查询这个视频的关联视频
            /* $play_info = model('VideoPlay') -> find($play_id);
            if($play_info -> play_type == 1 && $play_info -> father_play_id > 0){
                $map = [];
                $map['id'] = $play_id;
                $father_play_id = model('VideoPlay') -> find($play_id);
                $map1 = [];
                $map1['father_play_id'] = $play_info -> father_play_id;
                $list_play = model('VideoPlay') -> where($map)->whereOr($map1)->select();
            }

            
            dump($list_play);die; */
            if($play_type < 3){
                //会员添加
                if(!empty($goods_id_array)){
                    //关联相关不能超过3个
                    if(count($goods_id_array) > 3){
                        $this->error('关联商品最多不超过3个');
                    }else{
                        //插入数据
                        $rel = model('VideoPlayGoods') -> withoutAddData($play_id, $goods_id_array);
                        if($rel['code'] == 200){}else{
                            $this -> error('修改失败');
                        }
                    }
                }else{}
            }else{
                //系统添加
                if(!empty($goods_id_array)){
                    //关联相关不能超过3个
                    if(count($goods_id_array) > 3){
                        $this->error('关联商品最多不超过3个');
                    }else{
                        //插入数据
                        $rel = model('VideoPlayGoods') -> withoutAddData($play_id, $goods_id_array);
                        if($rel['code'] == 200){}else{
                            $this -> error('修改失败');
                        }
                    }
                }else{
                    $this->error('请选择关联商品');
                }
            }

			$rel = model('VideoPlay') -> editData($play_id, $main_title, $description,$cover_url='', $play_type, $is_immerse, $is_rotate, $play_status, $is_recommend, $is_original, $video_classid, $customLabel,$play_operation_status);//视频信息修改
			
			if($rel['code'] == 200){
				
				$this->success('修改成功');
			}else{
				$this -> error('修改失败');
			}
		}
		$viode_tags = '';
		$video_info = model('VideoPlay', 'model')->useGlobalScope(false)-> find($play_id);
		$video_info['label'] = model('VideoPlayLabelRelation') -> where('play_id', $play_id) -> column('id, label_id');
		$label_info = model('VideoPlayClassLabel') -> where('id', 'in', $video_info['label']) -> column('title');
		if(is_array($label_info))$viode_tags = implode(',', $label_info);

        //商品id
        $goods_info = ErpGoods::column('id,goods_name');
        //关联商品
        $goods_use_info = strval(implode(',',model('VideoPlayGoods')->where('play_id', $play_id) -> column('goods_id')));
		return ZBuilder::make('form')
            ->setPageTitle('视频编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'main_title', '主标题'],
                ['textarea', 'description', '视频描述'],
                //', 'play_type', '视频类型', '', [1 => '短视频', 2=> '长视频'], 1],
                ['radio', 'is_immerse', '是否沉浸', '', ['否', '是'], 0],
                ['radio', 'is_rotate', '是否旋转', '', ['否', '是'], 0],
                ['radio', 'play_status', '视频状态', '', ['禁用', '启用'], 0],
                ['radio', 'is_recommend', '首页推荐', '', ['否', '是'], 0],
                ['radio', 'is_original', '原创', '', ['转载', '原创'], 0],
				// ['select', 'video_classid', '视频分类', '所属分类', model('VideoPlayClass') -> getMenuTree(0, ''), $video_info -> video_classid],
				['tags', 'customLabel', '自定义标签','多个标签可以用英文 "," 号分割', $viode_tags],
            ])
			->addLinkages('video_classid', '视频分类', '', 'video_play_class', 2, $video_info['video_classid'], ['name' => 'title'])
			// ->addCheckbox('label', '所有标签', '', model('VideoPlayClassLabel') -> where('id', 'neq', 1)->column('id,title'))
            ->addSelect('goods_id_array', '选择关联商品[:请选择最多选择3个关联商品]', '', $goods_info,$goods_use_info, 'multiple')
            ->addHidden('play_operation_status',$video_info['play_operation_status'])
            ->addHidden('cover_url',$video_info['cover_url'])
            ->setFormData($video_info) // 设置表单数据
            ->fetch();
	}

    /**
     * PHP - 后端视频添加
     * @author dou <51779987@qq.com>
     */
    public function add($type=0)
    {
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post();
            //定义区分php上传还是前端上传
            $this->request->send_type = 1;
            //发布人id
            if($type == 1){
                $data['user_id']= $this->request->user_id  = intval(isset($data['user_id']) ? $data['user_id'] : '');//编辑发布人
            }else {
                $data['user_id'] = $this->request->user_id = intval(isset($data['user_id']) ? $data['user_id'] : 1);//系统发布人
            }
            $data['title']      = $this->request->title      = $data['main_title'];
            $data['is_immerse'] = $this->request->is_immerse = intval(isset($data["is_immerse"]) ? $data["is_immerse"] : 0);
            $data['is_rotate']  = $this->request->is_rotate  = intval(isset($data["is_rotate"]) ? $data["is_rotate"] : 0);
            $data['class_tage_array']  = $this->request->class_tage_array  = isset($data["customLabel"]) ? $data["customLabel"] : [];
            //封面图
            $data['cover_url'] = $cover_id = strval(isset($data["cover_url"]) ? $data["cover_url"] : '');
            //视频地址
            $data['file'] = strval(isset($data["file"]) ? $data["file"] : '');
            if($data["file"] != ''){
                //定义file_name
                $file_local_url = $_SERVER['DOCUMENT_ROOT']. get_file_path($data['file']);//视频地址(本地服务器)
                $data["file_name"]   = $this->request->file_name = $file_local_url;
            }

            //数据验证
            $Validate = validate('VideoApi', 'validate');
            if( !$Validate -> scene('add_video_info') -> check($data) ){
                $this->error($Validate -> getError(),'',(object)[]);
            }
            if($type == 1){
                //会员添加
                if(!empty($data['goods_id_array'])){
                    //关联相关不能超过3个
                    if(count($data['goods_id_array']) > 3){
                        $this->error('关联商品最多不超过3个');
                    }else{}
                }else{}
            }else{
                //系统添加
                if(!empty($data['goods_id_array'])){
                    //关联相关不能超过3个
                    if(count($data['goods_id_array']) > 3){
                        $this->error('关联商品最多不超过3个');
                    }else{}
                }else{
                    $this->error('请选择关联商品');
                }
            }

            //插入一条基础数据
            $rel_insert = controller('VideoApi','home')->get_create_upload_video_auth();
/*            $rel_insert['code'] = '200';
            $rel_insert['data']['playId'] = '2167';*/
            if($rel_insert['code'] == 200){
                //上传成功  拥有video_id  更新数据play_id
                $this->request->play_id    = intval(isset($rel_insert['data']['playId']) ? $rel_insert['data']['playId'] : 0);//trace($data["cover_url"], 'input_params');
                //封面图上传
                if($data["cover_url"] != ''){
                    //$data['cover_url']  = $this->request->cover_url  =  $this->request->domain(). get_file_path($data['cover_url']);
                    //获取本地路径
                    $cover_url = model('admin/Attachment') -> getFilePath($data['cover_url'], 1);
                    //上传OSS
                    $rel = controller('common/Osslogic', 'logic') -> uploadFile($cover_url, get_cover_pic_path($cover_url));
                    if($rel['code'] != 200) $this->error('封面图上传失败');
                    $data['cover_url']  = $this->request->cover_url = $rel['data']['info']['url'];
                    //删除本地附件
                    if($data['cover_url'] > 0) $rel = controller('common/Attachmentlogic', 'logic') -> delete($cover_id);//trace($cover_id, 'input_params');
                    //$body = json_encode($rel, true);
                    //trace($body, 'input_params');
                }
                //视频上传&videoId更新数据
                $rel = controller('VideoApi','home')->submit_video_info();
                if($rel['code'] == 200){
                    $this->success('新增视频成功', '', '_parent_reload');
                }else{
                    $this->error($rel['message']);
                }
            }else{
                $this->error($rel_insert['message']);
            }

        }

        // 使用ZBuilder快速创建表单
        $viode_tags = '';
        //商品id
        $goods_info = ErpGoods::column('id,goods_name');
        if($type == 1){
            //会员列表
            $user_info = model('user_center/Member', 'model\user')  -> column('uid,nick_name');
            //有编辑人
            return ZBuilder::make('form')
                ->setPageTitle('新增视频') // 设置页面标题
                ->addFile('file', '上传视频', '', '', '102400', '')
                ->addImage('cover_url', '自定义封面')
                ->addSelect('user_id', '选择视频发布人[:请选择最多选择1个发布人]', '', $user_info)
                ->addFormItems([ // 批量添加表单项
                    ['text', 'main_title', '主标题'],
                    ['textarea', 'description', '视频描述'],
                    ['radio',  'play_type', '视频类型', '', [1 => '短视频'], 1],//2=> '长视频'
                    /*['radio', 'is_immerse', '是否沉浸', 'hidden', ['否', '是'], 0],
                    ['radio', 'is_rotate', '是否旋转', '', ['否', '是'], 0],
                    ['radio', 'play_status', '视频状态', '', ['禁用', '启用'], 0],
                    ['radio', 'is_recommend', '首页推荐', '', ['否', '是'], 0],
                    ['radio', 'is_original', '原创', '', ['转载', '原创'], 0],*/
                    ['tags', 'customLabel', '自定义标签','多个标签可以用英文 "," 号分割', $viode_tags],
                    ])
                ->addLinkages('video_classid', '视频分类', '', 'video_play_class', 2, '', ['name' => 'title'])
                ->addSelect('goods_id_array', '选择关联商品[:请选择最多选择3个关联商品]', '', $goods_info, '', 'multiple')
                ->fetch();
        }else{
            //系统视频
            return ZBuilder::make('form')
                ->setPageTitle('新增视频') // 设置页面标题
                ->addFile('file', '上传视频', '', '', '102400', '')
                ->addImage('cover_url', '自定义封面')
                ->addFormItems([ // 批量添加表单项
                    ['text', 'main_title', '主标题'],
                    ['textarea', 'description', '视频描述'],
                    /*['radio',  'play_type', '视频类型', '', [1 => '短视频', 2=> '长视频'], 1],
                    ['radio', 'is_immerse', '是否沉浸', 'hidden', ['否', '是'], 0],
                    ['radio', 'is_rotate', '是否旋转', '', ['否', '是'], 0],
                    ['radio', 'play_status', '视频状态', '', ['禁用', '启用'], 0],
                    ['radio', 'is_recommend', '首页推荐', '', ['否', '是'], 0],
                    ['radio', 'is_original', '原创', '', ['转载', '原创'], 0],*/
                    ['tags', 'customLabel', '自定义标签','多个标签可以用英文 "," 号分割', $viode_tags],
                ])
                ->addHidden('play_type', 3)
                ->addLinkages('video_classid', '视频分类', '', 'video_play_class', 2, '', ['name' => 'title'])
                ->addSelect('goods_id_array', '选择关联商品[:请选择最多选择3个关联商品]', '', $goods_info, '', 'multiple')
                ->fetch();
        }
    }

}
